package com.example.tbag.healthcare.Activity;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;
import android.widget.ListView;

import com.example.tbag.healthcare.Adapter.MainListAdapter;
import com.example.tbag.healthcare.Model.Person;
import com.example.tbag.healthcare.R;
import com.example.tbag.healthcare.Util.CallPhoneUtil;
import com.example.tbag.healthcare.Util.DatabaseHelper;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SearchActivity extends AppCompatActivity {
    private int id;
    @BindView(R.id.list)
    ListView listView;
    @BindView(R.id.text)
    EditText editText;
    
    
    private DatabaseHelper helper = new DatabaseHelper(this);
    private List<Person> persons = new ArrayList<>();
    private MainListAdapter adapter;

    @OnClick(R.id.btn_back)
    public void back(){
        finish();
    }
    
    @OnClick(R.id.left_btn1)
    public void search(){
        persons.clear();
        getPersons(editText.getText().toString());
        adapter.notifyDataSetChanged();
    }


    public void getPersons(String text) {
        SQLiteDatabase db = helper.getReadableDatabase();
        Cursor cursor = db.query("people",null,"name like",new String[]{"%"+text+"%"},null,null,null);
        if (cursor != null && cursor.moveToFirst()) {
            persons.add(getPerson(cursor));
            while (cursor.moveToNext()) {
                persons.add(getPerson(cursor));
            }
            cursor.close();
            db.close();
        }
    }

    public Person getPerson(Cursor cursor) {
        int id = cursor.getInt(cursor.getColumnIndex("id"));
        String name = cursor.getString(cursor.getColumnIndex("name"));
        String type = cursor.getString(cursor.getColumnIndex("type"));
        String sex = cursor.getString(cursor.getColumnIndex("sex"));
        String age = cursor.getString(cursor.getColumnIndex("age"));
        String bedNum = cursor.getString(cursor.getColumnIndex("bedNum"));
        Person person = new Person(id, name, type, sex, age, bedNum);
        return person;
    }


    @OnClick(R.id.right_btn)
    public void callForHelp() {
        CallPhoneUtil.call(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        id = getIntent().getIntExtra("id",0);
        ButterKnife.bind(this);
        initListView();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void initListView() {
        adapter = new MainListAdapter(persons, this,id);
        listView.setAdapter(adapter);
    }

   

    
}
